<template>
  <div class="game-page">
    <view class="gameView" @click="gameTouchMiss">
      <image src="@/assets/images/game/game-background.png" class="gameBackground" />
      <view v-if="showMouse" class="gameItemView" :style="mousePosition" @click="gameItemHit">
        <image :key="mouseImage" class="gameItemImage" :src="mouseImage" />
      </view>
      <view v-if="showCountDown" class="countDownView">{{ countDown }}</view>
    </view>
    <view :key="score" class="singleScore">游戏时间: {{ score }}</view>
    <fixed-bottom :text="startOrStopText" @click="startOrStopAction" />
  </div>
</template>

<script>
import FixedBottom from '@/components/FixedBottom'
import mouseOut from '@/assets/images/game/game-come-out.png'
import mouseHit from '@/assets/images/game/game-hit.png'
import { saveReactionExam } from '../api'
import Taro from '@tarojs/taro'
import dayjs from 'dayjs'

export default {
  components: {
    FixedBottom
  },
  data() {
    return {
      title: '',
      mouseImage: mouseOut,
      position: [
        'top:26%;left:16.2%',
        'top:25%;left:41.2%',
        'top:26.5%;left:67%',
        'top:42.3%;left:12.5%',
        'top:42.3%;left:41.2%',
        'top:42.3%;left:67.6%',
        'top:60%;left:11.5%',
        'top:61%;left:41%',
        'top:61%;left:70.5%'
      ],
      mousePosition: '',
      showMouse: false,
      startOrStopText: '开始',
      countDown: 3, // 开始前的倒计时
      interval: '', // 定时器
      showCountDown: false,
      allCount: 0, // 总点击次数
      countsArrayIndex: 0,
      countsArray: ['10', '10', '10', '10', '10'],
      scoresArray: ['0.05', '0.05', '0.05', '0.05', '0.05'],
      timesArray: ['2.5', '2', '1.5', '1', '0.5'],
      hadEndGame: false,
      startTime: null,
      score: '00:00:00',
      timeInterval: null
    }
  },
  methods: {
    gameTouchMiss: function() {
    // console.log('miss:', this.countDown);
      if (this.countDown === 1) {
      // 进行下一次打地鼠布置
        clearInterval(this.interval)
        setTimeout(() => {
          if (!this.hadEndGame) {
            this.startHitMouse()
          }
        }, 300)
      }
    },

    gameItemHit: function(e) {
      e.stopPropagation()
      // 获取当前点中单个的分数
      this.mouseImage = mouseHit
      // 进行下一次打地鼠布置
      clearInterval(this.interval)
      setTimeout(() => {
        if (!this.hadEndGame) {
          this.startHitMouse()
        }
      }, 500)
    },

    randomNum: function(minNum, maxNum) {
      switch (arguments.length) {
        case 1:
          return parseInt(Math.random() * minNum + 1, 10)
        case 2:
          return parseInt(Math.random() * (maxNum - minNum + 1) + minNum, 10)
        default:
          return 0
      }
    },

    /**
   * 开始或结束游戏
   */
    startOrStopAction: function() {
      if (this.startOrStopText === '开始') {
        this.showCountDown = true
        this.countDownAction()
      } else { // 提交成绩
        this.endGame()
      }
    },

    countDownAction: function() {
      setTimeout(() => {
        const countDown = this.countDown - 1
        if (countDown === 0) {
          this.startOrStopText = '结束'
          this.showCountDown = false
          this.setTime()
          this.startHitMouse()
        } else {
          this.countDown = countDown
          this.countDownAction()
        }
      }, 1000)
    },

    setTime() {
      this.startTime = dayjs().startOf('day')
      this.timeInterval = setInterval(() => {
        this.startTime = this.startTime.add(1, 's')
        this.score = this.startTime.format('HH:mm:ss')
      }, 1000)
    },

    startHitMouse: function() {
      clearInterval(this.interval)
      // 最后一次已经跑完
      if (this.allCount >= parseInt(this.countsArray[this.countsArrayIndex]) && (this.countsArrayIndex >= this.countsArray.length - 1)) {
        clearInterval(this.interval)
        console.log('跑完了')
        this.showMouse = false
        this.countDown = 3
        this.endGame()
        return
      }
      if (this.allCount >= parseInt(this.countsArray[this.countsArrayIndex])) {
      // 跑完一个循环继续跑第二个
        this.allCount = 0
        this.countsArrayIndex += 1
      }
      this.allCount += 1
      // 时间间隔
      const timeSpace = parseFloat(this.timesArray[this.countsArrayIndex]) * 1000
      if (!timeSpace) return
      // 随机老鼠出现的位置
      this.mousePosition = this.position[this.randomNum(0, 8)]
      this.showMouse = true
      this.mouseImage = mouseOut
      const that = this
      this.interval = setInterval(() => {
        that.startHitMouse()
      }, timeSpace)
    },

    /**
   * 游戏结束，提交本次得分
   */
    endGame: function() {
      clearInterval(this.interval)
      if (this.hadEndGame) {
        return
      }
      this.hadEndGame = true
      this.timeInterval && clearInterval(this.timeInterval)

      const duration = parseInt(this.startTime.diff(dayjs().startOf('day'), 'm', true) + 0.5)
      wx.showModal({
        title: '游戏结束',
        content: '游戏时长：' + duration + '分钟',
        showCancel: false,
        confirmText: '好的',
        confirmColor: '#1DC06C',
        success: async(res) => {
          await saveReactionExam({
            duration,
            groupId: 'DDS'
          })
          this.showMsg('已保存', 'success')
          setTimeout(this.back, 1500)
        }
      })
    },
    onBackAction: function() {
      if (this.countDown === 1) {
        clearInterval(this.interval)
        const that = this
        Taro.showModal({
          content: '测试尚未结束，确定退出？',
          success(res) {
            if (res.confirm) {
              that.endGame()
            } else if (res.cancel) {
              that.startHitMouse()
            }
          }
        })
      } else {
        wx.navigateBack({
          delta: 1
        })
      }
    }
  }
}
</script>

<style lang="less">
@import './index.less';
</style>
